﻿Imports Microsoft.Win32
Imports System.Reflection
Imports System.ComponentModel

Public Class Configbase(Of T As New)
    Private _SoftwareKey As RegistryKey
    Private _MailNotifyKey As RegistryKey
    Private _Settings As RegistryKey
    Private _Accounts As RegistryKey
    Public Sub New()
        Me._SoftwareKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Me._MailNotifyKey = Me._SoftwareKey.CreateSubKey("MailNotify")
        Me._Settings = Me._MailNotifyKey.CreateSubKey("Settings")
    End Sub
    Public Sub New(ByVal account As String)
        Me._SoftwareKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Me._MailNotifyKey = Me._SoftwareKey.CreateSubKey("MailNotify")
        Me._Accounts = Me._MailNotifyKey.CreateSubKey("Accounts")
        Me._Settings = Me._Accounts.CreateSubKey(account)
    End Sub
    Public Sub DeleteAccount(ByVal account As String)
        Me._SoftwareKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Me._MailNotifyKey = Me._SoftwareKey.CreateSubKey("MailNotify")
        Me._Accounts = Me._MailNotifyKey.CreateSubKey("Accounts")
        Me._Accounts.DeleteSubKey(account, False)
    End Sub
    Public Sub SaveSettings(ByVal Settings As T)
        Dim propertyValue As String
        For Each CurrentProperty As PropertyInfo In Settings.GetType().GetProperties
            If CurrentProperty.CanRead Then
                propertyValue = CurrentProperty.GetValue(Settings, Nothing).ToString
                Me._Settings.SetValue(CurrentProperty.Name, propertyValue)
            End If
        Next
        Me._Settings.Close()
        Me._MailNotifyKey.Close()
        Me._SoftwareKey.Close()
    End Sub
    Public Function ReadSettings() As T
        Dim result As New T
        Dim PropertyValue As Object
        Dim converter As New TypeConverter
        For Each CurrentProperty As PropertyInfo In GetType(T).GetProperties
            If CurrentProperty.CanWrite Then
                PropertyValue = Me._Settings.GetValue(CurrentProperty.Name)
                If PropertyValue IsNot Nothing Then
                    CurrentProperty.SetValue(result, Convert.ChangeType(PropertyValue, CurrentProperty.PropertyType), Nothing)
                End If
            End If
        Next
        Return result
    End Function
    Public Shared Function GetAccounts() As List(Of T)
        Dim _result As New List(Of T)
        Dim _SoftwareKey As RegistryKey = Registry.CurrentUser.OpenSubKey("Software", True)
        Dim _MailNotifyKey As RegistryKey = _SoftwareKey.CreateSubKey("MailNotify")
        Dim _Accounts As RegistryKey = _MailNotifyKey.CreateSubKey("Accounts")
        Dim _Config As Configbase(Of T)
        For Each key As String In _Accounts.GetSubKeyNames
            _Config = New Configbase(Of T)(key)
            _result.Add(_Config.ReadSettings())
        Next
        Return _result
    End Function
End Class
